package com.qinglei.recoup.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.RadarFallDownDataDTO;
import com.qinglei.recoup.common.domain.RadarMessage;
import com.qinglei.recoup.common.domain.RadarVersionEnum;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.service.impl.TestRadarService;
import com.qinglei.recoup.common.utils.DateUtil;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.BedHealthDailyData;
import com.qinglei.recoup.system.domain.BedHealthDailyStatistics;
import com.qinglei.recoup.system.enums.BedStatusEnum;
import com.qinglei.recoup.system.enums.EventEnum;
import com.qinglei.recoup.system.pojo.BedStatusVO;
import com.qinglei.recoup.system.pojo.EventLogVO;
import com.qinglei.recoup.system.service.BedHealthDailyDataService;
import com.qinglei.recoup.system.service.BedHealthDailyStatisticsService;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("test")
@Api(tags = "测试用接口")
public class TestController {

    @Resource
    private BedHealthDailyDataService bedHealthDailyDataService;

    @Resource
    private BedHealthDailyStatisticsService bedHealthDailyStatisticsService;

    @Resource
    private BedService bedService;

    /**
     * STOMP对象
     */
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Resource
    private TestRadarService testRadarService;

    @ApiOperation(value = "模拟发送床位状态消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "status", value = "状态 0-离床 1-监测关闭 2-非监测时段 3-清醒 4-浅睡 5-深睡 6-离床 7-离床报警 8-处理中", paramType = "query", dataType = "Integer", required = true)
    })
    @GetMapping("sendBedStatus")
    public String sendBedStatus(Integer bedId, Integer status) {
        List<BedStatusVO> list = new ArrayList<>();
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-01床");
            bedStatusVO.setStatus(BedStatusEnum.DEVICE_OFFLINE.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.DEVICE_OFFLINE.getName());
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-02床");
            bedStatusVO.setStatus(BedStatusEnum.MONITOR_OFF.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.MONITOR_OFF.getName());
            bedStatusVO.setDescription("老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-03床");
            bedStatusVO.setStatus(BedStatusEnum.NON_IN_MONITOR.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NON_IN_MONITOR.getName());
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-04床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.CLEAR.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.CLEAR.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-08床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.LIGHT_SLEEP.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.LIGHT_SLEEP.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-09床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.DEEP_SLEEP.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.DEEP_SLEEP.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-05床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.OUT_BED.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.OUT_BED.getName());
            bedStatusVO.setDuration(132);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-06床");
            bedStatusVO.setStatus(BedStatusEnum.ALARM.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.AlarmEnum.OUT_BED_TOO_LONG.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.AlarmEnum.OUT_BED_TOO_LONG.getName());
            bedStatusVO.setEventId(109L);
            bedStatusVO.setDuration(182);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-07床");
            bedStatusVO.setStatus(BedStatusEnum.PROCESSING.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.PROCESSING.getName());
            bedStatusVO.setEventId(109L);
            bedStatusVO.setDuration(182);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }

        simpMessagingTemplate.convertAndSend("/topic/bedStatus." + bedId, list.get(status));
        return "ok";
    }

    @ApiOperation(value = "模拟发送床位状态消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "status", value = "状态 0-离床 1-监测关闭 2-非监测时段 3-清醒 4-浅睡 5-深睡 6-离床 7-离床报警 8-处理中", paramType = "query", dataType = "Integer", required = true)
    })
    @GetMapping("sendAllBedStatus")
    public String sendAllBedStatus(Integer bedId, Integer status) {
        List<BedStatusVO> list = new ArrayList<>();
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-01床");
            bedStatusVO.setStatus(BedStatusEnum.DEVICE_OFFLINE.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.DEVICE_OFFLINE.getName());
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-02床");
            bedStatusVO.setStatus(BedStatusEnum.MONITOR_OFF.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.MONITOR_OFF.getName());
            bedStatusVO.setDescription("老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病，老人外出看病");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-03床");
            bedStatusVO.setStatus(BedStatusEnum.NON_IN_MONITOR.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NON_IN_MONITOR.getName());
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-04床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.CLEAR.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.CLEAR.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-08床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.LIGHT_SLEEP.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.LIGHT_SLEEP.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-09床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.DEEP_SLEEP.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.DEEP_SLEEP.getName());
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-05床");
            bedStatusVO.setStatus(BedStatusEnum.NORMAL.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.NormalEnum.OUT_BED.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.NormalEnum.OUT_BED.getName());
            bedStatusVO.setDuration(132);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-06床");
            bedStatusVO.setStatus(BedStatusEnum.ALARM.getCode());
            bedStatusVO.setSubStatus(BedStatusEnum.AlarmEnum.OUT_BED_TOO_LONG.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.AlarmEnum.OUT_BED_TOO_LONG.getName());
            bedStatusVO.setEventId(109L);
            bedStatusVO.setDuration(182);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }
        {
            BedStatusVO bedStatusVO = new BedStatusVO();
            bedStatusVO.setBedId(bedId);
            bedStatusVO.setBedName("01层-01房-07床");
            bedStatusVO.setStatus(BedStatusEnum.PROCESSING.getCode());
            bedStatusVO.setStatusName(BedStatusEnum.PROCESSING.getName());
            bedStatusVO.setEventId(109L);
            bedStatusVO.setDuration(182);
            bedStatusVO.setCurMonitorTime("20:00-22:30");
            list.add(bedStatusVO);
        }

        simpMessagingTemplate.convertAndSend("/topic/allBedStatus." + 1, list.get(status));
        return "ok";
    }

    @ApiOperation(value = "模拟发送床位事件消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "query", dataType = "Integer", required = true),
    })
    @GetMapping("sendBedEvent")
    public String sendBedEvent(Integer bedId) {
        EventLogVO eventLogVO = new EventLogVO();
        eventLogVO.setEvtLogId(RandomUtils.nextLong());
        eventLogVO.setContent(EventEnum.getContent(RandomUtils.nextInt(1, 20)));
        eventLogVO.setTime(DateUtil.formatFullTime(LocalDateTime.now(), "yyyy年MM月dd日 HH:mm:ss"));
        eventLogVO.setIsAlarm(RandomUtils.nextInt(0, 1));
        eventLogVO.setIsStress(RandomUtils.nextInt(0, 1));
        simpMessagingTemplate.convertAndSend("/topic/bedEvent." + bedId, eventLogVO);
        return "ok";
    }

    @ApiOperation(value = "模拟全院床位及护工事件消息")
    @GetMapping("allBedEvent")
    public String allBedEvent(String msg, String snCode,String version){
        if (msg == null) {
            System.out.println("消息不能为空！");
        }
        BufferedReader out = null;
        BufferedReader br = null;
        try {

            ProcessBuilder pb = new ProcessBuilder(version);
            Process p = pb.start();
            out = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()), Charset.forName("GB2312")));
            br = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getErrorStream())));
            List<String> list = new ArrayList<>();
            String messageList;
            while ((messageList = out.readLine()) != null) {
                list.add(messageList);
            }
            for (int i = 3; i < list.size(); i++) {
                String message1 = list.get(i).substring(0, 25).trim();
                String message = list.get(i).substring(25, 35).trim();
                if (message1.startsWith(msg)) {
                    Runtime.getRuntime().exec(snCode + message);
                }
            }
            String estr = br.readLine();
            if (estr != null) {

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        return  "发送成功！";
    }

    @GetMapping("sendTourEvent")
    public String sendTourEvent(Integer tenId, String msg){
        simpMessagingTemplate.convertAndSend("/topic/tourEvent." + tenId, msg);
        return "ok";
    }

    @ApiOperation(value = "模拟添加监测仪设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "监测仪SN，8位16进制字符串，例：1122AADD", paramType = "query", dataType = "String", required = true),
    })
    @GetMapping("addRadar")
    public String addRadar(String sn) throws RedisConnectException {
        testRadarService.addDevice(sn);
        return "ok";
    }

    @ApiOperation(value = "模拟删除监测仪设备，可造成设备离线")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "监测仪SN，8位16进制字符串，例：1122AADD", paramType = "query", dataType = "String", required = true),
    })
    @GetMapping("delRadar")
    public String delRadar(String sn) throws RedisConnectException {
        testRadarService.delDevice(sn);
        return "ok";
    }

    @ApiOperation(value = "模拟监测仪设备离床状态，指定离床时间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "监测仪SN，8位16进制字符串，例：1122AADD", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "minutes", value = "指定离床时间，单位分钟", paramType = "query", dataType = "int", required = true),
    })
    @GetMapping("outBedRadar")
    public String outBedRadar(String sn, Integer minutes) throws RedisConnectException {
        testRadarService.change2OutBed(sn, minutes);
        return "ok";
    }

    @ApiOperation(value = "测试用添加健康数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "SN号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "day", value = "数据日期 格式:2021-01-10", paramType = "query", dataType = "String", required = true),
    })
    @GetMapping("addHealthData")
    public String addHealthData(String sn, String day) {
        Bed bed = bedService.getBedBySn(sn.toUpperCase());
        if (bed == null) {
            return "sn号不存在或没有绑定床位";
        }
        LocalDate statisticsDate = LocalDate.parse(day);
        bedHealthDailyStatisticsService.remove(Wrappers.<BedHealthDailyStatistics>lambdaQuery()
                .eq(BedHealthDailyStatistics::getBedId, bed.getId())
                .eq(BedHealthDailyStatistics::getStatisticsDate, statisticsDate));
        bedHealthDailyDataService.remove(Wrappers.<BedHealthDailyData>lambdaQuery()
                .eq(BedHealthDailyData::getBedId, bed.getId())
                .eq(BedHealthDailyData::getStatisticsDate, statisticsDate));

        BedHealthDailyStatistics bedHealthDailyStatistics = new BedHealthDailyStatistics();
        bedHealthDailyStatistics.setBedId(bed.getId());
        bedHealthDailyStatistics.setStatisticsDate(statisticsDate);

        bedHealthDailyStatistics.setDeepSleepDuration(RandomUtils.nextInt(0, 180));
        bedHealthDailyStatistics.setLightSleepDuration(RandomUtils.nextInt(0, 180));
        bedHealthDailyStatistics.setClearSleepDuration(RandomUtils.nextInt(0, 180));
        bedHealthDailyStatistics.setOutBedDuration(RandomUtils.nextInt(0, 180));
        bedHealthDailyStatistics.setSleepDuration(bedHealthDailyStatistics.getClearSleepDuration()
                + bedHealthDailyStatistics.getDeepSleepDuration()
                + bedHealthDailyStatistics.getLightSleepDuration()
                + bedHealthDailyStatistics.getOutBedDuration());

        if (bedHealthDailyStatistics.getOutBedDuration() != null && bedHealthDailyStatistics.getOutBedDuration() > 0) {
            bedHealthDailyStatistics.setOutBedNum(RandomUtils.nextInt(1, 20));
        }
        bedHealthDailyStatistics.setTurnOverNum(RandomUtils.nextInt(0, 100));
        bedHealthDailyStatisticsService.save(bedHealthDailyStatistics);

        BedHealthDailyData bedHealthDailyData = new BedHealthDailyData();
        bedHealthDailyData.setBedId(bed.getId());
        bedHealthDailyData.setStatisticsDate(statisticsDate);
        List<Integer> sleepData = new ArrayList<>(720);
        int lastSleep = RandomUtils.nextInt(1, 5);
        for (int i = 0; i < 720; i++) {
            if (RandomUtils.nextBoolean()) {
                if (RandomUtils.nextBoolean()) {
                    if (lastSleep != 4) {
                        lastSleep += 1;
                    }
                } else {
                    if (lastSleep != 1) {
                        lastSleep -= 1;
                    }
                }
            }
            sleepData.add(lastSleep);
        }
        bedHealthDailyData.setSleepData(JsonUtils.objectToJson(sleepData));

        List<Integer> heartPhaseData = new ArrayList<>(720);
        for (int i = 0; i < 720; i++) {
            heartPhaseData.add(RandomUtils.nextInt(23423, 34324));
        }
        bedHealthDailyData.setHeartPhaseData(JsonUtils.objectToJson(heartPhaseData));

        List<Integer> breathPhaseData = new ArrayList<>(720);
        for (int i = 0; i < 720; i++) {
            breathPhaseData.add(RandomUtils.nextInt(23423, 34324));
        }
        bedHealthDailyData.setBreathPhaseData(JsonUtils.objectToJson(breathPhaseData));

        List<Integer> turnOverData = new ArrayList<>(48);
        for (int i = 0; i < 48; i++) {
            turnOverData.add(RandomUtils.nextInt(0, 20));
        }
        bedHealthDailyData.setTurnOverData(JsonUtils.objectToJson(turnOverData));

        bedHealthDailyDataService.save(bedHealthDailyData);

        return "添加完成";
    }

    @GetMapping("importHealthData")
    public String importHealthData(String day) throws RecoupException {
        LocalDate statisticsDate;
        if (day == null) {
            statisticsDate = LocalDate.now().minusDays(1);
        } else {
            statisticsDate = LocalDate.parse(day);
        }
        bedHealthDailyStatisticsService.importDataFromOss(statisticsDate);
        return "OK";
    }


    @Resource
    private RadarDataService radarDataService;

    @PostMapping("/radarData")
    public String radarData(@RequestBody String data){
        RadarMessage radarMessage = new RadarMessage();
        radarMessage.setProCode(RadarVersionEnum.VERSION_V7.getCode());
        radarMessage.setData(data);
        radarDataService.saveRadarUserData(radarMessage);
        return "OK";
    }

    @GetMapping("/test111")
    public String test11(String sn,int exist,int l2){
        RadarFallDownDataDTO radarFallDownDataDTO = new RadarFallDownDataDTO();
        radarFallDownDataDTO.setExist(exist);
        radarFallDownDataDTO.setL2(l2);
        bedService.procRadarData(sn,radarFallDownDataDTO);
        return "OK";
    }


}
